package com.onetime.mall.trading.controller;

import com.alibaba.fastjson.JSONObject;
import com.onetime.mall.trading.constants.ErrorMsg;
import com.onetime.mall.trading.entity.UserEntity;
import com.onetime.mall.trading.service.UserService;
import com.onetime.mall.trading.utils.JwtUtils;
import com.onetime.mall.trading.utils.PageUtils;
import com.onetime.mall.trading.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户表
 *
 * @author liyixuan
 * @email liyixuan106@163.com
 * @date 2022-03-26 19:38:29
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

//    @Autowired
//    public void setUserController(UserService userService) {
//        this.userService = userService;
//    }

    /**
     * 登录，不安全，可伪造id，后期改进
     *
     * @param accountNumber
     * @param userPassword
     * @param response
     * @return
     */
    @RequestMapping("/login")
    public R login(@RequestParam("accountNumber") @NotEmpty @NotNull String accountNumber,
                   @RequestParam("userPassword") @NotEmpty @NotNull String userPassword,
                   HttpServletResponse response) {
        System.out.println("accountNumber" + accountNumber);
        System.out.println("userPassword" + userPassword);

        UserEntity user = userService.userLogin(accountNumber, userPassword);

        if (null == user) {
            /*查无此人*/
            return R.error(ErrorMsg.EMAIL_LOGIN_ERROR.getCode(), ErrorMsg.EMAIL_LOGIN_ERROR.getMsg());
        }
        if (user.isUserStatus()) {
            /*用户封禁*/
            return R.error(ErrorMsg.ACCOUNT_Ban.getCode(), ErrorMsg.ACCOUNT_Ban.getMsg());
        }
        user.setToken(JwtUtils.createJwt(user));
        /*System.out.println("登录：" + user);*/

//        /*新建一个Cookie对象，并赋予用户ID*/
//        Cookie cookie = new Cookie("shUserId", String.valueOf(user.getId()));
//        /*设置过期时间1天，以秒为单位*/
//        cookie.setMaxAge(24 * 60 * 60);
//        /*设同一服务器内所有应用都可访问到该Cookie*/
//        cookie.setPath("/");
//        /*设为true后，只能通过http访问，javascript无法访问,还可防止xss读取cookie*/
//        cookie.setHttpOnly(false);
//        cookie.setComment("用户登录信息存储");
//        /*保存cookie到客户端*/
//        response.addCookie(cookie);
        return R.ok().put("data", user);
    }

    @RequestMapping("/checkToken")
    public R checkToken(@RequestParam("token") @NotNull String token) {
        /*System.out.println("校验token=" + token);*/
        if (JwtUtils.checkJWT(token) != null) {
            return R.ok();
        }
        return R.error();
    }


    /**
     * // TODO: 2022/4/11  退出登录
     *
     * @param shUserId 用户ID
     * @param response
     * @return JSON
     */
    @RequestMapping("logout")
    public R logout(@RequestParam("userId")
                    @NotNull(message = "登录异常 请重新登录")
                    @NotEmpty(message = "登录异常 请重新登录") String shUserId,
                    HttpServletResponse response) {
//        /*cookie覆盖*/
//        Cookie cookie = new Cookie("shUserId", shUserId);
//        /*设置过期时间0天，以秒为单位*/
//        cookie.setMaxAge(0);
//        /*设同一服务器内所有应用都可访问到该Cookie*/
//        cookie.setPath("/");
//        /*设为true后，只能通过http访问，javascript无法访问,还可防止xss读取cookie*/
//        cookie.setHttpOnly(true);
//        /*保存cookie到客户端*/
//        response.addCookie(cookie);
        return R.ok();
    }


    /**
     * 注册账号
     *
     * @param user 前端传来的用户信息
     * @return JSON
     */
    @PostMapping("sign-in")
    public R signIn(@RequestBody UserEntity user) {
        System.out.println(user);
        /*设置注册时间*/
        user.setSignInTime(new Timestamp(System.currentTimeMillis()));
        /*设置用户头像*/
        if (user.getAvatar() == null || "".equals(user.getAvatar())) {
            user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
        }
        if (userService.userSignIn(user)) {
            return R.ok().put("data", user);
        }
        return R.error(ErrorMsg.REGISTER_ERROR.getCode(), ErrorMsg.REGISTER_ERROR.getMsg());
    }

    /**
     * 修改密码
     *
     * @param id          用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return JSON
     */
    @GetMapping("/password")
    public R updateUserPassword(@RequestParam("userId") @NotNull(message = "登录异常 请重新登录")
                                @NotEmpty(message = "登录异常 请重新登录") String id,
                                @RequestParam("oldPassword") @NotEmpty @NotNull String oldPassword,
                                @RequestParam("newPassword") @NotEmpty @NotNull String newPassword) {
        boolean result = userService.updatePassword(newPassword, oldPassword, Long.valueOf(id));
        if (result) {
            return R.ok();
        }
        return R.error(ErrorMsg.PASSWORD_RESET_ERROR.getCode(), ErrorMsg.PASSWORD_RESET_ERROR.getMsg());
    }

    /**
     * 修改用户公开信息
     *
     * @param id         用户ID
     * @param userEntity 新的用户类
     * @return JSON
     */
    @PostMapping("/info")
    public R updateUserPublicInfo(@RequestParam("userId") @NotNull(message = "登录异常 请重新登录")
                                  @NotEmpty(message = "登录异常 请重新登录") String id,
                                  @RequestBody UserEntity userEntity) {
        userEntity.setId(Long.valueOf(id));
        System.out.println("新的用户信息" + userEntity);
        if (userService.updateUserInfo(userEntity)) {
            return R.ok();
        }
        return R.error(ErrorMsg.SYSTEM_ERROR.getCode(), ErrorMsg.SYSTEM_ERROR.getMsg());
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        /*System.out.println("新的用户管理=" + params);*/
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        UserEntity user = userService.getById(id);

        return R.ok().put("user", user);
    }

    @RequestMapping("/get")
    public R get(@RequestParam("id") Long id) {
        UserEntity user = userService.getById(id);

        return R.ok().put("user", user);
    }

    /**
     * 获取用户信息
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("info")
    public R getOneUser(@RequestParam("userId")
                        @NotNull(message = "登录异常！请重新登录！")
                        @NotEmpty(message = "登录异常！请重新登录！") String id) {
        UserEntity user = userService.getById(Long.valueOf(id));
        return R.ok().put("data", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user) {
        Long id = user.getId();
        if (id == null) {
            userService.save(user);
        } else {
            userService.updateById(user);
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user) {
        userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody JSONObject jsonObject) {
        String id = jsonObject.getString("data");
        String substring = id.substring(1, id.length() - 1).replace(" ", "");
        String[] split = substring.split(",");
        List<Long> collect = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
        userService.removeByIds(collect);
        return R.ok();
    }


}
